"""
依赖注入（v1 版本 - 统一错误格式）
"""
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer
from motor.motor_asyncio import AsyncIOMotorDatabase
from jose import JWTError, jwt
from bson import ObjectId

from config.settings import settings
from database.connection import get_database
from models.response import ErrorCode
from utils.response import error

# OAuth2 配置
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/sac/v1/Auth/Login")


async def get_current_user(
    request: Request,
    token: str = Depends(oauth2_scheme),
    db: AsyncIOMotorDatabase = Depends(get_database)
) -> dict:
    """
    获取当前用户（通过 JWT Token）
    
    依赖注入函数，自动验证 Token 并返回当前用户信息
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail=error(
            request,
            "Authentication",
            "Auth",
            ErrorCode.INVALID_TOKEN,
            message="无效的认证凭据"
        ),
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    try:
        # 解码 Token
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        user_id: str = payload.get("sub")
        
        if user_id is None:
            raise credentials_exception
            
    except JWTError:
        raise credentials_exception
    
    # 查询用户
    user = await db.users.find_one({"_id": ObjectId(user_id)})
    
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=error(
                request,
                "Authentication",
                "Auth",
                ErrorCode.USER_NOT_FOUND,
                message="用户不存在"
            )
        )
    
    # 检查用户是否被禁用
    if user.get("disabled", False):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=error(
                request,
                "Authentication",
                "Auth",
                ErrorCode.USER_DISABLED,
                message="用户已被禁用"
            )
        )
    
    # 转换 _id 为 id
    user["id"] = str(user.pop("_id"))
    
    return user


async def get_current_active_user(
    current_user: dict = Depends(get_current_user)
) -> dict:
    """
    获取当前活跃用户（别名）
    """
    return current_user


async def get_current_admin(
    request: Request,
    current_user: dict = Depends(get_current_user)
) -> dict:
    """
    获取当前管理员用户
    
    验证当前用户是否为管理员角色
    """
    if current_user.get("role") != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=error(
                request,
                "Authorization",
                "Auth",
                ErrorCode.FORBIDDEN,
                message="需要管理员权限"
            )
        )
    
    return current_user

